package com.liser.southernstar.update;

import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.liser.southernstar.BuildConfig;
import com.liser.southernstar.update.install.DefaultAppInstaller;
import com.liser.southernstar.utils.AutoResetEvent;
import com.liser.southernstar.utils.HttpHandle;
import com.liser.southernstar.utils.RxJava2Task;

import java.nio.charset.StandardCharsets;

import io.reactivex.schedulers.Schedulers;

/**
 * APP升级
 */
public class AppUpdater {

    public static final String TAG = AppUpdater.class.getName();

    /**
     * 当前系统版本
     */
    public static final String CURRENT_VERSION = "1.0.0";

    private static final Object initLock = new Object();

    private static boolean isInit = false;

    private static boolean isExit = false;

    private static AutoResetEvent are = new AutoResetEvent(true);

    /**
     * 更新线程
     */
    private static void updateThread() {
        new RxJava2Task<Void>((emitter) -> {
            for (; ; ) {
                // 每十分钟检查一次线程
                try {
                    are.waitOne(600000);
                } catch (Exception ignored) {
                }
                // 是否已退出
                if (isExit) {
                    break;
                }
                try {
                    // 检查版本更新
                    JSONObject version = JSONObject.parseObject(new String(HttpHandle.getInstance().get(UpdateServerUrls.Version), StandardCharsets.UTF_8));
                    String versionName = version.getString("version");
                    if (BuildConfig.VERSION_NAME.equals(versionName)) {
                        continue;
                    }
                    // 进行下载并安装
                    DefaultAppInstaller.downloadAndInstall(versionName);
                } catch (Exception ex) {
                    Log.e(TAG, "更新出错：", ex);
                }
            }
        }, Schedulers.io()).subscribeOnce();
    }

    /**
     * 获取到权限之后初始化
     */
    public static void initOnPermissionGranted() {
        synchronized (initLock) {
            if (isInit || isExit) {
                return;
            }
            isInit = true;
        }
        updateThread();
    }

    /**
     * 退出自动更新
     */
    public static void exit() {
        synchronized (initLock) {
            isExit = true;
            are.set();
        }
    }
}
